工作上有時候需要檢查Android網路狀態, 常常會使用到ping指令
這篇紀錄一下使用app來執行ping的動作
主要實作了一個 PingAsyncTask 來ping由其他class (Activity, Fragment or Service)傳過來的網址
並且把ping的結果透過自定的interface回傳回去
class如下:
public class PingAsyncTask extends AsyncTask<String, Void, String>{
private final String TAG = "PingAsyncTask";
private ITaskComplete mListener;
private Context mContext;
ProgressDialog mPD;
public PingAsyncTask(ITaskComplete listener, Context ctx){
mListener = listener;
mContext = ctx;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//
if (mContext != null) {
mPD = ProgressDialog.show(mContext, "Please wait", "Running PING command ...");
}
}
@Override
protected String doInBackground(String... addresses) {
StringBuffer results = new StringBuffer();
for(String addr : addresses) {
try {
results.append(executePingCommand(addr));
} catch (Exception e) {
Log.d(TAG, e.toString());
}
}
return results.toString();
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (mListener != null) {
mListener.onTaskCompleted(result);
}
if (mPD != null && mPD.isShowing()) {
mPD.dismiss();
}
Log.d(TAG, "result :\n" + result);
}
private String executePingCommand(String address){
Runtime runtime = Runtime.getRuntime();
try
{
Process mPingProcess = runtime.exec("/system/bin/ping -c 2 -w 6 " + address);
int mExitValue = mPingProcess.waitFor();
Log.d(TAG, "mExitValue "+mExitValue+" for " + address);
StringBuffer pingResult = new StringBuffer();
InputStreamReader reader = new InputStreamReader(mPingProcess.getInputStream());
BufferedReader buffer = new BufferedReader(reader);
String line = "";
while ((line = buffer.readLine()) != null) {
pingResult.append(line + "\n");
}
pingResult.append("PING " + address +
((mExitValue == 0) ? " succeed!\n" : "failed!\n"));
pingResult.append("ExitValue = " + mExitValue + "\n");
return pingResult.toString();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return "Exception during ping " + address + "!\n";
}